package com.obsidian.basic.weather;

import com.alibaba.fastjson.JSON;
import com.obsidian.basic.weather.ws.ArrayOfString;
import com.obsidian.basic.weather.ws.WeatherWebService;
import com.obsidian.basic.weather.ws.WeatherWebServiceSoap;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * 主要测试wdsl文件在本地，生成客户端代码及调用
 *
 * @author obsidian
 * @ClassName:CxfClient
 * @Description:webservice客户端： 该类提供两种不同的方式来调用webservice服务
 * 1：代理工厂方式
 * 2：动态调用webservice
 * @date:2018年4月10日下午4:14:07
 */
public class CxfWeatherClient {


    public static void main(String[] args) {
        proxyF();
        /*try {
            dynamicF();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }*/
    }

    /**
     * 1.代理类工厂的方式,需要拿到对方的接口地址
     */
    public static void proxyF() {
        try {
            // 接口地址
            String address = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
            // 代理工厂
            JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
            // 设置代理地址
            jaxWsProxyFactoryBean.setAddress(address);
            // 设置接口类型
            jaxWsProxyFactoryBean.setServiceClass(WeatherWebServiceSoap.class);
            // 创建一个代理接口实现
            WeatherWebServiceSoap weatherWebServiceSoap = (WeatherWebServiceSoap) jaxWsProxyFactoryBean.create();
            ArrayOfString supportProvince = weatherWebServiceSoap.getSupportProvince();
            System.out.println("返回结果:" + supportProvince.getString());
            /*测试不成功*/
//            ArrayOfString s = weatherWebServiceSoap.getWeatherbyCityName("成都");
//            System.out.println("返回结果:" + s.getString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 2：动态调用
     */
    public static void dynamicF() throws MalformedURLException {
        // 创建动态客户端
        URL url = new URL("file:/E:/IdeaProjects/webservice-file-transport/webservice-basic/src/main/resources/WeatherWebService.wsdl");
        // String address = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(url);
        // Client client = dcf.createClient(address);
        // 需要密码的情况需要加上用户名和密码
        // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
        try {
            // invoke("方法名",参数1,参数2,参数3....);
            Object[] objects = client.invoke("getSupportProvince");
            System.out.println("返回数据:" + JSON.toJSONString(objects));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}